package com.imooc.bilibili.support;

import com.imooc.bilibili.exception.ConditionException;
import com.imooc.bilibili.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;

@Component
public class UserSupport {

    /**
     * 获取当前用户的登录信息id
     */
    public Map<String, Long> getCurrnetUserId() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = requestAttributes.getRequest().getHeader("token");
        //对token进行校验
        boolean signed = JwtUtil.isSigned(token);
        if (!signed) {
            throw new ConditionException("此token并不是正确的token");
        }
        boolean verify = JwtUtil.verify(token);
        if (!verify) {
            throw new ConditionException("token的签名并不正确");
        }
        boolean expired = JwtUtil.isExpired(token);
        if (expired) {
            throw new ConditionException("token已经过期");
        }
        Long loginId = (Long) JwtUtil.getClaim(token).get("loginId");
        Long userId = (Long) JwtUtil.getClaim(token).get("userId");
        if (null != loginId && loginId < 0) {
            throw new ConditionException("登录用户为非法用户");
        }
        if (null != userId && userId < 0) {
            throw new ConditionException("用户信息非法");
        }

        Map<String, Long> map = new HashMap<>();
        map.put("loginId", loginId);
        map.put("userId", userId);
        return map;
    }


}
